﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PPI.Client.Logic;
using PPI.Client.Logic.Delegate;
using PPI.Client.Logic.XML;
using PPI.Client.Utils;
using PPI.Entities.Enumerator;
using PPI.Entities.XML;
using PPI.General;

namespace PPI.Client.Presenter
{
    public interface ICopyMobileDatabase
    {
        int ProgressBarValue { set; }
        event EventHandler<EventArgs> StartCopy;
        string SelectedPathToCopy{ get;}
        void ReloadOutboxFolders();
        string ErrorMessage{ set;}
    }

    public class CopyMobileDatabasePresenter
    {
        private UpdateBar m_DelegateUpdateCopybar;

        private ICopyMobileDatabase m_View;

        public CopyMobileDatabasePresenter(ICopyMobileDatabase view)
        {
            m_View = view;
            Initilize();
        }

        private void Initilize()
        {
            m_DelegateUpdateCopybar = new UpdateBar(UpdateCopyBar);
            m_View.StartCopy += new EventHandler<EventArgs>(m_View_StartCopy);
        }

        #region Events

        void m_View_StartCopy(object sender, EventArgs e)
        {
            try
            {
                string _errorMessage = "";



                if (ValidateDatabase(ref _errorMessage))
                {
                    CopyDatabase();
                }
                else
                {
                    m_View.ErrorMessage = _errorMessage;
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        
        #endregion

        private void CopyDatabase()
        {
            try
            {
                DirectoryInfo _selectedDirectory = new DirectoryInfo(m_View.SelectedPathToCopy);
                EXmlOutboxBase _database = LOutbox.GetXmlOutboxBase(DirHelper.GetSdfPath(_selectedDirectory.FullName));
                Random random = new Random();
                string _destinationFolderName = m_View.SelectedPathToCopy.Substring(m_View.SelectedPathToCopy.LastIndexOf("\\") + 1) + "_" + random.Next(int.MinValue, int.MaxValue).ToString();
                DirectoryInfo _destinationDirectory = new DirectoryInfo(_database.OutboxPath + "\\" + _destinationFolderName);
                Application.DoEvents();
                LOutbox.CopyMobileDatabase(_selectedDirectory, _destinationDirectory, true, m_DelegateUpdateCopybar);
                Application.DoEvents();
                LXmlOutbox _serviceXml = new LXmlOutbox(_database);
                _serviceXml.InsertNode(_database, _destinationDirectory);
                
                switch (_database.DatabaseType) 
                {
                    case DatabaseTypes.GPS:
                        PPI.Mobile.General.MobileGeneral.AddAuditableColumns(_database.ConnectionString);
                        break;
                    case DatabaseTypes.Inspection:
                        PPI.Mobile.General.MobileGeneral.AddAuditableInspectionColumns(_database.ConnectionString);
                        break;
                    case DatabaseTypes.DistributionGPS:
                    case DatabaseTypes.DistributionInspection:
                        PPI.Mobile.General.MobileGeneral.AddAuditableDistributionColumns(_database.ConnectionString);
                        break;

                }

                m_View.ReloadOutboxFolders();
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private bool ValidateDatabase(ref string messageError)
        {
            StringBuilder _errorMessage = new StringBuilder();
            bool _foundError = false;

            DirectoryInfo _SelectedDirectory = new DirectoryInfo(m_View.SelectedPathToCopy);
            if (!_SelectedDirectory.Exists)
            {
                _foundError = true;
                _errorMessage.AppendLine("The folder doesn´t exist");
            }
            if (_SelectedDirectory.GetDirectories("Images").Length == 0)
            {
                _foundError = true;
                _errorMessage.AppendLine("The folder images doesn´t exist");
            }
            if (_SelectedDirectory.GetFiles("*.sdf").Length != 1)
            {
                _foundError = true;
                _errorMessage.AppendLine("The database file doesn´t exist");
            }

            if (_SelectedDirectory.GetFiles("*.sdf").Length == 1)
            {
                if (LOutbox.GetXmlOutboxBase(DirHelper.GetSdfPath(_SelectedDirectory.FullName)) == null)
                {
                    _foundError = true;
                    _errorMessage.AppendLine("The database type was not detected. This might occur because the database is not updated  with the latest version. Please contact your system administrator.");
                }
            }
            messageError = _errorMessage.ToString();

            return !_foundError;
        }

        private void UpdateCopyBar(int percetage)
        {
            m_View.ProgressBarValue = percetage;
        }

    }
}
